package com.xiaomili.halfsugar.fragment;


import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.AppBarLayout.OnOffsetChangedListener;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.xiaomili.halfsugar.R;
import com.xiaomili.halfsugar.adapter.CategoryFragmemtPagerAdapter;
import com.xiaomili.halfsugar.adapter.CommonHolder;
import com.xiaomili.halfsugar.adapter.CommonRecyclerViewAdapter;
import com.xiaomili.halfsugar.bean.CategoryBean;
import com.xiaomili.halfsugar.bean.CategoryBean.DataBean.CategoryListBean;
import com.xiaomili.halfsugar.bean.HotRecmmandBean;
import com.xiaomili.halfsugar.bean.HotRecmmandBean.DataBean;
import com.xiaomili.halfsugar.utils.LogUtils;
import com.xiaomili.halfsugar.utils.OKHttpUtils;
import com.xiaomili.halfsugar.utils.OKHttpUtils.MyCallback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ProductFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ProductFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @InjectView(R.id.appBarLayout)
    AppBarLayout mAppBarLayout;
    @InjectView(R.id.ptr_refresh)
    PtrClassicFrameLayout mPtrRefresh;

    private String mParam1;
    private String mParam2;

    private Activity mActivity;
    private List<Fragment> mDatas;
    private List<String> mStrings1;
    private List<String> mStrings2;


    @InjectView(R.id.vp_category)
    ViewPager mVpCategory;
    @InjectView(R.id.rg_container)
    RadioGroup mRgContainer;
    @InjectView(R.id.recycler_hot_recommand)
    RecyclerView mRecyclerHotRecommand;

    public ProductFragment() {
        // Required empty public constructor
    }

    public static ProductFragment newInstance(String param1, String param2) {
        ProductFragment fragment = new ProductFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDatas = new ArrayList<>();
        mStrings1 = new ArrayList<>();
        mStrings2 = new ArrayList<>();
        mActivity = getActivity();
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            LogUtils.i(mParam1);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_product, container, false);
        ButterKnife.inject(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPtrRefresh.post(new Runnable() {
            @Override
            public void run() {
                mPtrRefresh.autoRefresh();
            }
        });
        //设置RadioGroup的监听事件
        mRgContainer.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton mRadioButton = (RadioButton) group.findViewById(checkedId);
                mRadioButton.setChecked(true);
                int position = group.indexOfChild(mRadioButton);
                mVpCategory.setCurrentItem(position);
            }
        });
        //加载Category的数据
        loadCategoryData();
        mPtrRefresh.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //加载HotRecommand的数据
                loadHotRecommandData();
                mPtrRefresh.refreshComplete();
            }
        });


        //如果AppBarLayout相对于顶部的偏移量小于0则不刷新,否则刷新
        if (mAppBarLayout != null) {
            mAppBarLayout.addOnOffsetChangedListener(new OnOffsetChangedListener() {
                @Override
                public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    if (mPtrRefresh == null) return;
                    mPtrRefresh.setEnabled((verticalOffset >= 0) ? true : false);
                }
            });
        }
    }


    //加载数据
    private void loadCategoryData() {
        OKHttpUtils.newInstance(mActivity).obtainDataAsyncByGet(mParam1, new MyCallback() {
            @Override
            public void onFailure(IOException e) {
                LogUtils.i("网络加载失败");

            }

            @Override
            public void onResponse(String result) {
                LogUtils.i("下载结果" + result);
                CategoryBean categoryBean = new Gson().fromJson(result, CategoryBean.class);
                List<CategoryListBean> listBeen = categoryBean.data.category_list;
                for (int i = 0; i < listBeen.size(); i++) {
                    if (i < 6) {
                        mStrings1.add(listBeen.get(i).pic);
                    } else {
                        mStrings2.add(listBeen.get(i).pic);
                    }
                }
                mDatas.add(ComCategoryFragment.newInstance((ArrayList<String>) mStrings1));
                mDatas.add(ComCategoryFragment.newInstance((ArrayList<String>) mStrings2));
                mVpCategory.setAdapter(new CategoryFragmemtPagerAdapter(getChildFragmentManager(), mDatas));
                mVpCategory.addOnPageChangeListener(new OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        ((RadioButton)mRgContainer.getChildAt(position)).setChecked(true);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        });
    }

    //加载HotRecommand的数据
    private void loadHotRecommandData() {
        OKHttpUtils.newInstance(mActivity).obtainDataAsyncByGet(mParam2, new MyCallback() {
            @Override
            public void onFailure(IOException e) {

            }

            @Override
            public void onResponse(String result) {
                HotRecmmandBean hotRecmmandBean = new Gson().fromJson(result, HotRecmmandBean.class);
                mRecyclerHotRecommand.setLayoutManager(new GridLayoutManager(mActivity, 3));
                List<DataBean> data = hotRecmmandBean.data;
                LogUtils.i("data.size" + data.size());
                mRecyclerHotRecommand.setAdapter(new CommonRecyclerViewAdapter<DataBean>(mActivity,
                        data, R.layout.item_recycler_com_product_hot_rcmd) {
                    @Override
                    public void bindData(CommonHolder holder, int position, DataBean bean) {
                        ImageView imageView = holder.findViewById(R.id.iv_item);
                        Picasso.with(mActivity).load(bean.mini_pic_url).into(imageView);
                    }
                });
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
